#pragma once
#include<iostream>
using namespace std;


template<class K>
struct BSTNode
{
	BSTNode(const K& key)
		:_key(key)
		, _left(nullptr)
		, _right(nullptr)
	{}
	K _key;
	BSTNode<K>* _left;
	BSTNode<K>* _right;
};

template<class K>
class BSTree
{
	typedef BSTNode<K> Node;
public:
	void Insert(const K& key)
	{
		Node* cur = _root;
		Node* curp = nullptr;
		if (cur == nullptr)
		{
			_root = new Node(key);
			return;
		}
		while (cur)
		{
			if (cur->_key < key)
			{
				curp = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				curp = cur;
				cur = cur->_left;
			}
			else
			{
				return;
			}
		}
		cur = new Node(key);
		if (curp->_key < key)
		{
			curp->_right = cur;
		}
		else
		{
			curp->_left = cur;
		}
	}

	void Erase(const K& key)
	{
		if (_root == nullptr)
		{
			return;
		}
		Node* cur = _root;
		Node* curp = nullptr;
		while (cur)
		{
			if (cur->_key < key)
			{
				curp = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				curp = cur;
				cur = cur->_left;
			}
			else
			{
				if (cur->_left == nullptr)
				{
					if (curp == nullptr)
					{
						_root = cur->_right;
					}
					else
					{
						if (cur == curp->_left)
						{
							curp->_left = cur->_right;
						}
						else
							curp->_right = cur->_right;

					}
					
					delete cur;
					return;
				}
				else if (cur->_right == nullptr)
				{
					if (curp == nullptr)
					{
						_root = cur->_left;
					}
					else
					{
						if (cur == curp->_left)
						{
							curp->_left = cur->_left;
						}
						else
							curp->_right = cur->_left;

					}
					
					delete cur;
					return;
				}
				else
				{
					Node* parent = cur;
					Node* rightmin = cur->_right;
					while (rightmin->_left)
					{
						parent = rightmin;
						rightmin = rightmin->_left;
					}
					cur->_key = rightmin->_key;
					if(parent->_right == rightmin)
						parent->_right = rightmin->_right;
					else
						parent->_left = rightmin->_right;

					delete rightmin;
					return;
				}			
				
			}
		}
	}
	bool Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{			
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				cur = cur->_left;
			}
			else
			{
				return true;
			}
		}
		return false;
	}
	void _InOder()
	{
		InOder(_root);
	}
private:

	void InOder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}
		InOder(root->_left);
		cout << root->_key << " ";
		InOder(root->_right);
	}
	Node* _root = nullptr;
};

